using AutoMapper;
using Microsoft.EntityFrameworkCore;
using PowerManage.Entity;
using PowerManage.EntityFrameworkCore;
using PowerManage.Entity.Dtos.Roles;
using PowerManage.Entity.Dtos.Users;
using PowerManage.Repository;

namespace PowerManage.Service.Impl;

/// <summary>
/// 用户仓储实现
/// </summary>
public class UserService : BaseService, IUserService
{
    private readonly ApplicationDbContext _dbContext;
    private readonly IMapper _mapper;
    private readonly IBaseRepository<EleUser> _userRepository;

    public UserService(ApplicationDbContext dbContext, IMapper mapper, IBaseRepository<EleUser> userRepository)
    {
        _dbContext = dbContext;
        _mapper = mapper;
        _userRepository = userRepository;
    }

    /// <summary>
    /// 根据用户名搜索，分页返回用户列表
    /// </summary>
    /// <param name="userPageReqDto"></param>
    /// <returns></returns>
    public async Task<UserPageRspDto> GetUserPageAsync(UserPageReqDto userPageReqDto)
    {
        //创建返回对象
        var result = new UserPageRspDto();
        // 获取所有用户记录的查询对象 延迟执行(在需要时才执行)
        var query = _dbContext.Users.AsQueryable();
        if (!string.IsNullOrEmpty(userPageReqDto.Name))
        {
            query = query.Where(user => user.UserName != null && user.UserName.Equals(userPageReqDto.Name));
        }

        // 页数至少为1
        userPageReqDto.CurrentPage = userPageReqDto.CurrentPage > 0 ? userPageReqDto.CurrentPage : 1;
        //获取总数和用户列表
        var count = await query.CountAsync();
        var userList = await query.OrderByDescending(x => x.CreationTime)
            .Skip((userPageReqDto.CurrentPage - 1) * userPageReqDto.PageSize)
            .Take(userPageReqDto.PageSize) //取每页大小条记录
            .ToListAsync();
        //填充返回对象
        result.CurrentPage = userPageReqDto.CurrentPage;
        result.PageSize = userPageReqDto.PageSize;
        result.TotalCount = count;
        //循环转换
        var userDtos = new List<UserDto>();
        foreach (var user in userList)
        {
            var userDto = _mapper.Map<UserDto>(user);
            //填充创建者 从这些用户中找到第一个符合条件的用户
            var creator = _dbContext.Users.FirstOrDefault(x => x.Id == userDto.Id);
            userDto.Creator = _mapper.Map<UserDto>(creator);
            //填充角色列表 查询与用户关联的所有角色
            var roleList = await (
                from ur in _dbContext.UserRoles
                join r in _dbContext.Roles on ur.RoleId equals r.Id
                where ur.UserId == user.Id
                select r //最终选择角色表中的角色对象
            ).ToListAsync();
            userDto.Roles = _mapper.Map<List<RoleDto>>(roleList);
            userDtos.Add(userDto);
        }

        result.Users = userDtos;
        return result;
    }

    /// <summary>
    /// 获取用户角色列表
    /// </summary>
    public async Task<List<string>> GetRoleList(string? userName)
    {
        var roleList = await (from r in _dbContext.Roles
            join ur in _dbContext.UserRoles on r.Id equals ur.RoleId
            join u in _dbContext.Users on ur.UserId equals u.Id
            where u.UserName == userName
            select r.Name).ToListAsync();
        return roleList;
    }

    /// <summary>
    /// 获取所有用户列表
    /// </summary>
    /// <returns></returns>
    public List<UserAllDto> GetAll()
    {
        var eleUsers = _userRepository.GetAll();
        return _mapper.Map<List<UserAllDto>>(eleUsers);
    }
}